package org.ypx.shared.util;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.ypx.center.service.IUserService;
import org.ypx.db.entity.User;

/**
 * @author Yan Peixuan
 * @date 2017/3/31 20:17
 * @description
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private IUserService userService;

    //    权限验证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String loginName = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(userService.findRoles(loginName));
        authorizationInfo.setStringPermissions(userService.findRight(loginName));
        return authorizationInfo;
    }

    //身份验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String loginName = (String) token.getPrincipal();
        User user = userService.findByLoginName(loginName);
        if (user == null) {
            throw new UnknownAccountException();//没找到帐号
        }
        /*if (Boolean.TRUE.equals(user.getLocked())) {
            throw new LockedAccountException(); //帐号锁定
        }*/
        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以在此判断或自定义实现
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user.getLoginName(), //用户名
                user.getPassword(), //密码
                ByteSource.Util.bytes("username+salt"),//salt=username+salt
                getName()  //realm name
        );
        return authenticationInfo;
    }
}
